#!/bin/sh

SRC_DIR=`dirname $0`
source $SRC_DIR/env.sh

ALLOC_UNIT=16777216
INTERVAL=0.5

DBNAME=$1
MAX_FILES=$2
if [ -z "`echo $MAX_FILES | egrep '^[0-9]*$'`" ]; then
  MAX_FILES=2
fi

if [ ! "$USER" == "mongod" ]; then
  echo "this script should be kicked by mongod user."
  exit -1
fi

if [ ! -f $DBPATH/$DBNAME.1 ]; then
  echo "datbase [$DBNAME] does not exist"
  exit -1
fi

echo "preallocate $MAX_FILES files for $DBNAME"

CNT=2
while [ $CNT -le $MAX_FILES ]; do
  FILE=$DBPATH/$DBNAME.$CNT
  if [ ! -f $FILE ]; then
    if [ $CNT -eq 2 ]; then SIZE=268435456; fi
    if [ $CNT -eq 3 ]; then SIZE=536870912; fi
    if [ $CNT -eq 4 ]; then SIZE=1073741824; fi
    if [ $CNT -ge 5 ]; then SIZE=2146435072; fi
    echo "preallocate $FILE with $SIZE bytes."
    touch $FILE
    chmod 600 $FILE
    # append $ALLOC_UNIT with $INTERVAL interval
    while [ `stat -c %s $FILE` -lt `expr $SIZE - $ALLOC_UNIT` ]; do
      head -c $ALLOC_UNIT /dev/zero >> $FILE
      sleep $INTERVAL
    done
    LAST_SIZE=`stat -c %s $FILE`
    head -c `expr $SIZE - $LAST_SIZE` /dev/zero >> $FILE
  fi
  CNT=`expr $CNT + 1`
done

